package com.cpi.cornpp.plantversion.services;

import java.util.Iterator;
import java.util.List;

import com.cpi.cornpp.common.exception.CornPPException;
import com.cpi.cornpp.plantversion.converter.PlantVersionConverter;
import com.cpi.cornpp.plantversion.dao.PlantVersionDAO;
import com.cpi.cornpp.plantversion.dto.PlantVersionDTO;
import com.cpi.cornpp.plantversion.exception.PlantVersionException;
import com.cpi.cornpp.plantversion.view.PlantVersionView;

/**
 * Plant Version Service
 * @author Edgar Joao
 *
 */
public class PlantVersionService {
	/**
	 * @author Edgar Joao
	 * @param versionId
	 * @return
	 * @throws PlantVersionException
	 */
	public List getPlantsVersions(int versionId) throws PlantVersionException{
		PlantVersionDAO plantVersionDAO = null;
		List listOfPlantsVersions = null;
		PlantVersionConverter plantVersionConverter = null;		
		try{
			plantVersionDAO = new PlantVersionDAO();			
			plantVersionConverter = new PlantVersionConverter();
			listOfPlantsVersions = plantVersionConverter.convertDTOsToViews(plantVersionDAO.getPlantsVersions(versionId));										
		} catch (PlantVersionException plantVersionException) {
			throw plantVersionException;
		} catch (Exception e){
			PlantVersionException plantVersionException = null;
			e.printStackTrace(System.out);
			plantVersionException = new PlantVersionException(e , CornPPException.LAYER_SERVICE,CornPPException.ACTION_LISTS);
			throw plantVersionException;
		}	
		return listOfPlantsVersions;
	}
	/**
	 * @author Edgar Joao
	 * @param dto
	 * @throws PlantVersionException
	 */
	public void updatePlantsVersions(List plantsVersionsList) throws PlantVersionException{		
		Iterator iterator = null;
		PlantVersionDAO plantVersionDAO = null;
		PlantVersionConverter plantVersionConverter = null;
		PlantVersionDTO plantVersionDTO = null;
		PlantVersionView plantVersionView = null;		
		try{
			iterator = plantsVersionsList.iterator();
			plantVersionDAO = new PlantVersionDAO();
			plantVersionConverter = new PlantVersionConverter();
			while(iterator.hasNext()){
				plantVersionView = (PlantVersionView) iterator.next();
				plantVersionDTO = plantVersionConverter.converterPlantVersionViewToDto(plantVersionView);
				plantVersionDAO.updatePlantsVersions(plantVersionDTO);
			}			
		} catch (PlantVersionException plantVersionException) {
			throw plantVersionException;
		} catch (Exception e){
			PlantVersionException plantVersionException = null;
			e.printStackTrace(System.out);
			plantVersionException = new PlantVersionException(e , CornPPException.LAYER_SERVICE,CornPPException.ACTION_LISTS);
			throw plantVersionException;
		}	
	}
}
